package 字符串;

import java.util.HashMap;

/**
 * @Author Weton Li
 * @Date 2021/8/26 21:50
 */
public class 拼写单词 {
    public static void main(String[] args) {
        String chars = "atach";
        String[] words = {"cat", "bt", "hat", "tree"};
        System.out.println(countCharacters(words,chars));
    }

    public static int countCharacters(String[] words, String chars) {
        HashMap<Character, Integer> charsCnt = new HashMap<>();
        int res = 0;
        int len = chars.length();
        for (int i = 0; i < len; i++) { // 将chars中的字母放入map中
            char c = chars.charAt(i);
            charsCnt.put(c, charsCnt.getOrDefault(c, 0) + 1);
        }
        for (String word : words) {
            HashMap<Character, Integer> wordCnt = new HashMap<>();
            int length = word.length();
            for (int i = 0; i < length; i++) { // 将strings中每个字符串分别放到map中
                char c = word.charAt(i);
                wordCnt.put(c, wordCnt.getOrDefault(c, 0) + 1);
            }
            boolean isAns = true;
            for (int i = 0; i < length; i++) {
                char c = word.charAt(i);
                if (wordCnt.getOrDefault(c, 0) > charsCnt.getOrDefault(c, 0)) {
                    isAns = false;
                    break;
                }
            }
            if (isAns) {
                res += word.length();
            }
        }
        return res;
    }
}
